require(['jquery', 'underscore','Mustache','Utils', 'echarts', 'echarts/chart/bar', 'echarts/chart/line', 'modal'],
function($, _, Mustache, Utils, ec) {
	$("#btn-blog-next").click(function () {
      $('#blogCarousel').carousel('next')
    });

    $("#btn-blog-prev").click(function () {
      $('#blogCarousel').carousel('prev')
    });

    $("#btn-client-next").click(function () {
      $('#clientCarousel').carousel('next')
    });

    $("#btn-client-prev").click(function () {
      $('#clientCarousel').carousel('prev')
    });
    
    $('.viewRow').hide();
    $('.configRow').hide();
    //$('.viewRow')[0].style.display="block";
    //$('.configRow')[0].style.display="block";
    sourceContainer = '<row id="sourceRow"><div class="panel panel-success panel-source">'
                    +'<div class="panel-heading">'
                    +'<h3 class="panel-title">{{typeName}}数据源-共<span id="{{typeName}}SourceCount">{{typeCount}}</span>个'
                    +'<button class="btnnew noty" onClick="showAdd(\'{{typeName}}\')">添加</button></h3>'
                    +'</div>'
                    +'<div class="panel-body panel-{{typeName}}"></div></div></row>'

    sourceTpl = '<div class="col-sm-3 col-lg-3">'
                    +    '<div class="dash-unit" id="sourceUnit{{index}}">'
                    +         '<dtitle><span>'
                    +           '{{source}} <button class="btn btn-danger" style="float:right;" onClick="deleteSource({{index}})">删除</button>'
                    +         '</span></dtitle>'
                    +         '<hr style="margin-top: 1.5rem;margin-bottom: 0rem;">'
                    +         '<div onClick="showUpdate({{index}})"><div class="info-user" >'
                    +             '<img src="/image/icon/Database-icon.png" style="width:50%; height: 50%; margin-top: 2rem"/>'
                    +         '</div>'
                    +         '<div class="cont">'
                    +             '{{#content}}<p>{{key}}: {{value}}</p>{{/content}}'
                    +         '</div> </div>'
                    +     '</div>'
                    + '</div>'

    window.dMetaCtx = new Object();
    window.Mustache = Mustache;
    window._ = _;
    
    refreshSource(function(res){});
});

function refreshSource(cb) {
    $.getJSON('/api/source', function(res) {
        var infoList = res.infoList;
        var panelList = res.panelList;
        var sourceTypeCount = res.sourceTypeCount;
        window.dMetaCtx.infoList = infoList;
        window.dMetaCtx.sourceTypeCount = sourceTypeCount;
        window.dMetaCtx.sourceWords = res.sourceWords;
        window.dMetaCtx.sourceClass = res.sourceClass;

        InfoList = infoList;


        var dashboardContent = ''
        _.each(sourceTypeCount, function(e, i) {
            dashboardContent += Mustache.render(sourceContainer, {typeName: i, typeCount: e});
        });
        $('#sourceRow').html(dashboardContent);
        _.each(infoList, function(e, i) {
            var content = [];
            _.each(panelList[i], function(e, i) {
                content.push({key: i, value: e});
            });
            $('.panel-'+e.SOURCE).append(Mustache.render(sourceTpl,
                {source: e.SOURCE, index: i, content: content}));
        });
        cb(res);
    });
}


function clickSource() {
    $('.chooseLabel').removeClass('active');
    $('.chooseLabel').removeClass('chooseLabel');
    $('#sourceLabel').addClass('active');
    $('#sourceLabel').addClass('chooseLabel');

    $('.panel-source').fadeIn(300);
    $('.viewRow').hide();
    $('.configRow').hide();
}

function clickView() {
    $('.chooseLabel').removeClass('active');
    $('.chooseLabel').removeClass('chooseLabel');
    $('#viewLabel').addClass('active');
    $('#viewLabel').addClass('chooseLabel');

    $('.panel-source').hide();
    $('.viewRow').fadeIn(300);
    $('.configRow').hide();
}

function clickConfig() {
    $('.chooseLabel').removeClass('active');
    $('.chooseLabel').removeClass('chooseLabel');
    $('#configLabel').addClass('active');
    $('#configLabel').addClass('chooseLabel');

    $('.panel-source').hide();
    $('.viewRow').hide();
    $('.configRow').fadeIn(300);
}

function showAdd(typeName) {
    var classTpl = '<div class="form-group">'
                        +'<label>class</label>'
                        +'<input type="text" class="form-control" id="{{typeName}}className" name="className" value="{{className}}">'
                        +'</div>';
    var modalTpl = '<div class="form-group">'
                        +'<label for="{{typeName}}{{word}}">{{word}}</label>'
                        +'<input type="text" class="form-control" id="{{typeName}}{{word}}" name="{{word}}">'
                        +'</div>';

    var words = dMetaCtx.sourceWords[typeName];
    var className = dMetaCtx.sourceClass[typeName];
    dMetaCtx.typeName = typeName;
    $('#addSourceName').text(typeName);
    $('#addForm').html(Mustache.render(classTpl, {className: className}));
    var len = words.length;
    for (var i = 0; i < len; ++i) {
        var wordi = words[i];
        if (wordi == "SOURCE" || wordi == "className") {
            continue;
        }
        $('#addForm').append(Mustache.render(modalTpl, {typeName: typeName, word: wordi}));
    }
    $('#addModal').modal();
}

function showUpdate(index) {
    var modalTpl = '<div class="form-group">'
                        +'<label for="{{typeName}}{{word}}">{{word}}</label>'
                        +'<input type="text" class="form-control" id="{{typeName}}{{word}}" name="{{word}}" value="{{value}}">'
                        +'</div>';

    var infoList = dMetaCtx.infoList;
    var typeName = infoList[index].SOURCE;
    var words = dMetaCtx.sourceWords[typeName];
    var className = dMetaCtx.sourceClass[typeName];

    dMetaCtx.updateIndex = index;

    $('#updateSourceName').text(typeName);
    var form = ''
    
    var len = words.length;
    for (var i = 0; i < len; ++i) {
        var wordi = words[i];
        if (wordi == "SOURCE") {
            continue;
        }
        form += Mustache.render(modalTpl, {typeName: typeName, word: wordi, value: infoList[index][wordi]});
    }
    $('#updateForm').html(form);
    $('#updateModal').modal();
}

function addSource() {
    var typeName = dMetaCtx.typeName;
    var words = dMetaCtx.sourceWords[typeName];
    var className = dMetaCtx.sourceClass[typeName];
    $.post('/api/source/add', {
        'label': className,
        'words': $('#addForm').serialize(), 
        }, function(res) {
            if (res == "0") {
                alert('添加失败');
            } else {
                refreshSource(function(){});
                alert('添加成功');
            }
            $('#addModal').modal('hide');
    });
}

function updateSource() {
    var index = dMetaCtx.updateIndex;
    var id = dMetaCtx.infoList[index].id;
    $.post('/api/source/update', {
        'label': id,
        'words': $('#updateForm').serialize(),
        }, function(res) {
            if (res == "0") {
                alert('更新失败');
            } else {
                refreshSource(function(){});
                alert('更新成功');
            }
            $('#updateModal').modal('hide');
    });
}

function deleteSource(index) {
	if(!confirm("确定删除这个数据源？"))
		return;
    var id = dMetaCtx.infoList[index].id;
    var typeName = dMetaCtx.infoList[index].SOURCE;
    $.post('/api/source/delete', {
        'label': id,
        }, function(res) {
            if (res == "0") {
                alert('删除失败');
            } else {
                $('#sourceUnit'+index).parent().fadeOut(200);
                var countId = '#'+typeName+'SourceCount';
                var number = parseInt($(countId).text()) - 1;
                $(countId).text(number.toString());
                alert('删除成功');
            }
    });
}


